package controllerGoods

import (
	"github.com/gin-gonic/gin"
	goods_pb "mxshop/api/goods/v1"
	dtoGoods "mxshop/app/mxshop_api/api/internal/domain/dto/goods"
	"mxshop/gmicro/pkg/common/core"
	translatorGin "mxshop/pkg/translator/gin"
	"net/http"
	"strconv"
)

func (gc *GoodsController) CategoryList(ctx *gin.Context) {
	ret, err := gc.srv.Goods().Category().GetAllCategorysList(ctx)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.JSON(http.StatusOK, ret)
	return
}

func (gc *GoodsController) CategoryDelete(ctx *gin.Context) {
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	if err := gc.srv.Goods().Category().DeleteCategory(ctx, idInt); err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.Status(http.StatusOK)
	return
}

func (gc *GoodsController) CategoryDetail(ctx *gin.Context) {
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	ret, err := gc.srv.Goods().Category().GetSubCategory(ctx, &goods_pb.CategoryListRequest{
		Id: int32(idInt),
	})
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	ctx.JSON(http.StatusOK, ret)
	return
}

func (gc *GoodsController) CategoryNew(ctx *gin.Context) {
	categoryForm := dtoGoods.CategoryDTO{}
	if err := ctx.ShouldBindJSON(&categoryForm); err != nil {
		translatorGin.HandleValidatorError(ctx, err, gc.trans)
		return
	}

	ret, err := gc.srv.Goods().Category().CreateCategory(ctx, &categoryForm)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.JSON(http.StatusOK, ret)
	return
}

func (gc *GoodsController) CategoryUpdate(ctx *gin.Context) {
	categoryForm := dtoGoods.CategoryDTO{}
	if err := ctx.ShouldBindJSON(&categoryForm); err != nil {
		translatorGin.HandleValidatorError(ctx, err, gc.trans)
		return
	}

	if err := gc.srv.Goods().Category().UpdateCategory(ctx, &categoryForm); err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.Status(http.StatusOK)
	return
}
